var goodsRecordCtrl = new XFApp.client();
XFApp.client.prototype.goodsRecord = {
	hgGoods : [],
	customers :[],
	successCode : "10000",
	hgPage : null,
	cusPage : null,
	urlItems : {
		queryHgGoodsByPageURL : basePath + "/packagestats/goodsRecord/queryHgGPage",
		queryCustomerByPageURL : basePath + "/packagestats/goodsRecord/queryCusPage",
		submitGoodsRUL : basePath +"/packagestats/goodsRecord/submitGoods",
		saveGoodsRUL : basePath +"/packagestats/goodsRecord/saveGoods"
	},
	initSelect : function(){
		$("#mUnitSelect").bsSuggest({
			idField: "dictcode",  
			keyField: "dictname",
			effectiveFields :["dictcode","dictname"],
			effectiveFieldsAlias:{dictcode:"编码",dictname:"名称"},
		    data: {
		        'value':currencys,
		    }
		   });
		$("#unit").bsSuggest({
			idField: "dictcode",  
			keyField: "dictname",
			effectiveFields :["dictcode","dictname"],
			effectiveFieldsAlias:{dictcode:"编码",dictname:"名称"},
	        data: {
	           'value':units,
	        }
	   });
		$("#unit1").bsSuggest({
			idField: "dictcode",  
			keyField: "dictname",
			effectiveFields :["dictcode","dictname"],
			effectiveFieldsAlias:{dictcode:"编码",dictname:"名称"},
	        data: {
	           'value':units,
	        }
	   });
		$("#unit2").bsSuggest({
			idField: "dictcode",  
			keyField: "dictname",
			effectiveFields :["dictcode","dictname"],
			effectiveFieldsAlias:{dictcode:"编码",dictname:"名称"},
	       data: {
	           'value':units,
	       }
	   });
		$("#customSelect").bsSuggest({
			idField: "dictcode",  
			keyField: "dictname",
			effectiveFields :["dictcode","dictname"],
			effectiveFieldsAlias:{dictcode:"编码",dictname:"名称"},
	       data: {
	           'value':customerCodes,
	       }
	   });
	},
	initViewByGoods : function(){
		_this = this;
		$("input[type='text']").each(function(){
			if(!!$(this).attr("name") && !!sku_goods[$(this).attr("name")]){
				$(this).val(sku_goods[$(this).attr("name")]);
			}
		});
		if(!!sku_goods.id){
			$("span.readonly").each(function(){
				var val = "";
				if(!!sku_goods[$(this).attr("name")]){
					val = sku_goods[$(this).attr("name")];
				}
				if($(this).hasClass("dataTime") && !!val){
					val = val.replace("T"," ");
				}
				if(!!val){
					$(this).text(val);
				}
			});
			var goods_status = "";
			for(index in stats_goodsStatus){
				var goodsStatus = stats_goodsStatus[index];
				if(goodsStatus.dictcode == sku_goods.docketstatus ){
					goods_status = goodsStatus.dictname;
				}
			}
			$("#docketstatus").text(goods_status);
			var apply_status = "";
			for(index in stats_approves){
				var approves = stats_approves[index];
				if(approves.dictcode == sku_goods.applystatus){
					apply_status = approves.dictname;
				}
			}
		
			$("#applystatus_des").text(apply_status);
		}else{
			$("#base_info span.readonly").each(function(){
				var val = "";
				if(!!sku_goods[$(this).attr("name")]){
					val = sku_goods[$(this).attr("name")];
				}
				if($(this).hasClass("dataTime") && !!val){
					val = val.replace("T"," ");
				}
				if(!!val){
					$(this).text(val);
				}
			});
			$("span[name='docketCode']").text("");
		}
		$("#customSelect").attr("data-id",sku_goods["customscode"]);
		$("#customSelect").val(_this.selCustomerValue(sku_goods["customscode"]));
		$("#unit").attr("data-id",sku_goods["unit"]);
		$("#unit").val(_this.selUnitValue(sku_goods["unit"]));
		$("#unit1").attr("data-id",sku_goods["unit1"]);
		$("#unit1").val(_this.selUnitValue(sku_goods["unit1"]));
		$("#unit2").attr("data-id",sku_goods["unit2"]);
		$("#unit2").val(_this.selUnitValue(sku_goods["unit2"]));
		$("#mUnitSelect").attr("data-id",sku_goods["currency"]);
		$("#mUnitSelect").val(_this.selCurrencyValue(sku_goods["currency"]));
		
	},
	selCustomerValue : function(val){
		var text ;
		for(index in customerCodes){
			var code = customerCodes[index];
			if(code.dictcode == val){
				text = code.dictname;
			}
		}
		return text;
	},
	selUnitValue : function(val){
		var text ;
		for(index in units){
			var unit = units[index];
			if(unit.dictcode == val){
				text = unit.dictname;
			}
		}
		return text;
	},
	selCurrencyValue : function(val){
		var text ;
		for(index in currencys){
			var currency = currencys[index];
			if(currency.dictcode == val){
				text = currency.dictname;
			}
		}
		return text;
	},
	validForm : function(){
		var flag = true;
		$("span[required='required']").each(function(){
			if(!$(this).html()){
				flag = false;
				$(this).nextAll(".null_error").show();
			}
		});
		$("input[required='required']").each(function(){
			if(!$(this).val()){
				flag = false;
				$(this).nextAll(".null_error").show();
			}	
		});
		if(!$("#mUnitSelect").attr("data-id")){
			$("#mUnitSelect_span").show();
			flag = false;
		}
		if(!$("#customSelect").attr("data-id")){
			$("#customscode_span").show();
			flag = false;
		}
		
		if(!$("#unit").attr("data-id")){
			$("#unit_span").show();
			flag = false;
		}
		if(!$("#unit1").attr("data-id")){
			$("#unit1_span").show();
			flag = false;
		}
		
		$("input[isnumber='true']").each(function(){
			var reg = /^\d+(\.\d{1,5})?$/;
			if(!!$(this).val() && !reg.test($(this).val())){
				flag = false;
				$(this).nextAll(".type_error").show();
			}
		});
		var selectAlert = false;
		$("input.sug_select").each(function(){
			if(!!$(this).val() && !$(this).attr("data-id")){
				flag = false;
				selectAlert = true;
			}
			if(!$(this).val() && !!$(this).attr("data-id")){
				$(this).attr("data-id","");
			}
		});
		if(selectAlert){
			 $.alert({
  	  	        title: '温馨提示',
  	  	        content: '请选择正确的选项!',
  	  	        confirmButtonClass: 'btn-info',
  	  	        confirmButton: '确定',
  	  	        columnClass: 'col-md-4 col-md-offset-4'
  	  	    });
		}
		return flag;
	},
	queryPage : function(){
		_this = this;
		var params = {
			gcode : $("#gcodeFilter").val(),
			gname : $("#gnameFilter").val()
		}
		if(!!_this.hgPage){
			_this.hgPage.page("remote",0,params);
		}else{
			_this.hgPage = $("#page").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryHgGoodsByPageURL,
			        params: params, 
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		_this.hgGoods = pageResult.itemList;
			        		$("#data_grid").html($("#dataTmp").render(pageResult.itemList));
			        	}else{
			        		  $.alert({
			        	  	        title: '温馨提示',
			        	  	        content: '数据查询失败!',
			        	  	        confirmButtonClass: 'btn-info',
			        	  	        confirmButton: '确定',
			        	  	        columnClass: 'col-md-4 col-md-offset-4'
			        	  	    });
			        	}
			        },
			        error : function(){
			      	  $.alert({
			    	        title: '温馨提示',
			    	        content: '数据查询失败!',
			    	        confirmButtonClass: 'btn-info',
			    	        confirmButton: '确定',
			    	        columnClass: 'col-md-4 col-md-offset-4'
			    	    });
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	queryCusPage : function(){
		_this = this;
		var params = {
			docketCode : $("#customercodeFilter").val(),
			docketName : $("#customernameFilter").val()
		}
		if(!!_this.cusPage){
			_this.cusPage.page("remote",0,params);
		}else{
			_this.cusPage = $("#customer_page").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryCustomerByPageURL,
			        params: params, 
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		_this.customers = pageResult.itemList;
			        		$("#customer_data_grid").html($("#cusDataTmp").render(pageResult.itemList));
			        	}else{
			        		  $.alert({
			        	  	        title: '温馨提示',
			        	  	        content: '数据查询失败!',
			        	  	        confirmButtonClass: 'btn-info',
			        	  	        confirmButton: '确定',
			        	  	        columnClass: 'col-md-4 col-md-offset-4'
			        	  	    });
			        	}
			        },
			        error : function(){
			      	  $.alert({
			    	        title: '温馨提示',
			    	        content: '数据查询失败!',
			    	        confirmButtonClass: 'btn-info',
			    	        confirmButton: '确定',
			    	        columnClass: 'col-md-4 col-md-offset-4'
			    	    });
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	
	
	isSubmiting : false,
	goodsSubmit : function(){
		_this = this;
		if(!_this.validForm()){
			return;
		}
		this.generalSubmitGoods(_this.urlItems.submitGoodsRUL,"提交");
		this.isSubmiting = false;
	},
	goodsSave : function(){
		if(!_this.validForm()){
			return;
		}
		this.generalSubmitGoods(_this.urlItems.saveGoodsRUL,"暂存");
		this.isSubmiting = false;
	},
	
	generalSubmitGoods : function(url,type){
		if(this.isSubmiting){
			return;
		}
		this.isSubmiting = true;
		var docket = {};
		var errText = "";
		$("input[type='text']").each(function(){
			if($(this).hasClass("sug_select")){
				docket[$(this).attr("name")] = $(this).attr("data-id");
			}else{
				docket[$(this).attr("name")] = $(this).val();
			}
		});

		$("#base_info span[type='text']").each(function(){
			if(!!$(this).text()){
				docket[$(this).attr("name")] = $(this).text();
			}
		});

		$.confirm({
		    title: '温馨提示',
		    content: '是否确认'+type+'?',
		    columnClass: 'col-md-4 col-md-offset-4',
		    confirmButtonClass: 'btn-info',
	  	    confirmButton: '确定',
	  	    cancelButton: '取消',
		    confirm: function(){
		    	$.ajax({
					url:url,
					data:docket,//JSON.stringify(docket),
					//contentType: 'application/json',
					dataType:'json',
					type:'post',
					success:function(data){
						if(data.code!=10000){
							  $.alert({
			        	  	        title: '温馨提示',
			        	  	        content: data.msg,
			        	  	        confirmButtonClass: 'btn-info',
			        	  	        confirmButton: '确定',
			        	  	        columnClass: 'col-md-4 col-md-offset-4'
			        	  	    });
						}else{
							  if(type=="提交"){
								  $("#submit_btn").hide();
								  $("#save_btn").hide();
							  }
							  $.alert({
			        	  	        title: '温馨提示',
			        	  	        content: type+"成功",
			        	  	        confirmButtonClass: 'btn-info',
			        	  	        confirmButton: '确定',
			        	  	        columnClass: 'col-md-4 col-md-offset-4'
			        	  	  });
							  /**
							   * 重刷页面数据
							   */
							  sku_goods = JSON.parse(data.result);
							  goodsRecordCtrl.goodsRecord.initViewByGoods(); 
						}
					},
					error:function(){
						  $.alert({
		      	  	        title: '温馨提示',
		      	  	        content: type+"出现异常,请联系开发人员",
		      	  	        confirmButtonClass: 'btn-info',
		      	  	        confirmButton: '确定',
		      	  	        columnClass: 'col-md-4 col-md-offset-4'
		      	  	    });
					}
				});
		    }
		    
		});
	
		
	},
	/**
	 * 联动选择海关商品信息
	 */
	selGcode : function(gcode){
		var selHggoods = null;
		for(var index = 0;index<this.hgGoods.length;index++){
			var tmpGoods = this.hgGoods[index];
			if(tmpGoods.gcode == gcode){
				selHggoods = tmpGoods;
				break;
			}
		}
		/**
		 * 联动填充数据
		 */
		if(!!selHggoods){
			$("input[name='gcode']").val(selHggoods.gcode);
			$("input[name='gname']").val(selHggoods.gname);
			
			$("#unit").attr("data-id",selHggoods.unit1);
			$("#unit").val(_this.selUnitValue(selHggoods.unit1));
			$("#unit1").attr("data-id",selHggoods.unit1);
			$("#unit1").val(_this.selUnitValue(selHggoods.unit1));
			$("#unit2").attr("data-id",selHggoods.unit12);
			$("#unit2").val(_this.selUnitValue(selHggoods.unit2));
		}
		$("#choose_goods_modal").modal('hide'); 
	},
	/**
	 * 联动选择海关商品信息
	 */
	selCustomer : function(cusNo){
		var selCustomer = null;
		for(var index = 0;index<this.customers.length;index++){
			var tmpCustomer = this.customers[index];
			if(tmpCustomer.docketCode == cusNo){
				selCustomer = tmpCustomer;
				break;
			}
		}
		/**
		 * 联动填充数据
		 */
		if(!!selCustomer){
			$("#customer_name_span").hide();
			$("input[name='customercode']").val(selCustomer.docketCode||"");
			$("span[name='customername']").text(selCustomer.docketname||"");
			$("span[name='ebpcode']").text(selCustomer.ebpcode||"");
			$("span[name='ebpname']").text(selCustomer.ebpname||"");
			$("span[name='ebccode']").text(selCustomer.ebccode||"");
			$("span[name='ebcname']").text(selCustomer.ebcname||"");
			$("span[name='agentcode']").text(selCustomer.agentcode||"");
			$("span[name='agentname']").text(selCustomer.agentname||"");
		}
		$("#choose_customer_modal").modal('hide'); 
	},
	/**
	 * 绑定页面事件
	 */
	event : function(){
		_this = this;
		$("#goods_choose").on("click",function(){
			$("#choose_goods_modal").modal();
		});
		$("#btn_customer_choose").on("click",function(){
			$("#choose_customer_modal").modal();
		});
		$("#btn_customer_remove").on("click",function(){
			$("input[name='customercodeFilter']").val("");
			$("input[name='customernameFilter']").val("");
			$("input[name='customercode']").val("");
			$("span[name='customername']").val("");
			
			$("span[name='ebpcode']").val("");
			$("span[name='ebpname']").val("");
			$("span[name='ebccode']").val("");
			$("span[name='ebcname']").val("");
			$("span[name='agentcode']").val("");
			$("span[name='agentname']").val("");
		});
		$("#btn_goods_remove").on("click",function(){
			$("input[name='gcodeFilter']").val("");
			$("input[name='gnameFilter']").val("");
			$("input[name='gcode']").val("");
			$("input[name='gname']").val("");
			$("select[name='unit']").val("");
			$("select[name='unit1']").val("");
			$("select[name='unit2']").val("");
		});
		$("#submit_btn").on("click",function(){
			_this.goodsSubmit();
		});
		$("#save_btn").on("click",function(){
			_this.goodsSave();
		});
		$("#goods_search").on("click",function(){
			_this.queryPage();
		});
	
		$("#goods_reset").on("click",function(){
			$("input[name='gcodeFilter']").val("");
			$("input[name='gnameFilter']").val("");
		});
		$("#custom_serach").on("click",function(){
			_this.queryCusPage();
		
		});
	
		$("#custom_reset").on("click",function(){
			$("input[name='customercodeFilter']").val("");
			$("input[name='customernameFilter']").val("");
		});
		$("input[required='required']").on("focus",function(){
			$(this).nextAll("span").hide();
		});
		$("input[required='required']").on("focus",function(){
			$(this).nextAll("span").hide();
		});
		$("#mUnitSelect").on("focus",function(){
			$("#mUnitSelect_span").hide();
		});
	},
}

$(function(){
	goodsRecordCtrl.goodsRecord.event();
	goodsRecordCtrl.goodsRecord.initSelect();
	if(!!sku_goods){
		goodsRecordCtrl.goodsRecord.initViewByGoods();
	}
});